package com.gis3c.sys.security.shiro.token;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

public class HmacSHA256Utils {
	public static String digest(String key, String content) 
			throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
		Mac mac = Mac.getInstance("HmacSHA256");
        byte[] secretByte = key.getBytes("utf-8");
        byte[] dataBytes = content.getBytes("utf-8");

        SecretKey secret = new SecretKeySpec(secretByte, "HMACSHA256");
        mac.init(secret);

        byte[] doFinal = mac.doFinal(dataBytes);
        byte[] hexB = new Hex().encode(doFinal);
        
        
        
        return new String(hexB, "utf-8");
    }

    public static String digest(String key, Map<String, ?> map) 
    		throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
        StringBuilder s = new StringBuilder();
        for(Object values : map.values()) {
            if(values instanceof String[]) {
                for(String value : (String[])values) {
                    s.append(value);
                }
            } else if(values instanceof List) {
                for(String value : (List<String>)values) {
                    s.append(value);
                }
            } else {
                s.append(values);
            }
        }
        return digest(key, s.toString());
    }
}
